package com.wsoft.bpm.listener.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wsoft.bpm.entity.ActWorkflowConfigEntity;
import com.wsoft.bpm.query.node.TaskCandidateQuery;
import com.wsoft.bpm.query.node.TaskQuery;
import com.wsoft.bpm.service.IActWorkflowConfigService;
import com.wsoft.bpm.utils.ActivityUtils;
import com.wsoft.constant.CommonConstant;
import com.wsoft.entity.BaseEntity;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;

/**
 * 用户任务候选人表达式监听器
 *
 * @Author zhonglj
 * @Date 2025/1/10 8:39
 */
@Service("taskCandidateExpressionListener")
public class TaskCandidateExpressionListener implements TaskListener {
    @Resource
    private TaskService taskService;
    @Resource
    private IActWorkflowConfigService workflowConfigService;

    @Override
    public void notify(DelegateTask delegateTask) {
        ActWorkflowConfigEntity config = workflowConfigService.getOne(Wrappers.lambdaQuery(ActWorkflowConfigEntity.class)
                .eq(ActWorkflowConfigEntity::getProcDefId, delegateTask.getProcessDefinitionId())
                .eq(ActWorkflowConfigEntity::getActId, delegateTask.getTaskDefinitionKey())
                .eq(BaseEntity::getDeleted, CommonConstant.YESNO_NO)
        );

        if (config != null && StrUtil.isNotBlank(config.getJson())) {
            TaskQuery taskQuery = JSONUtil.toBean(config.getJson(), TaskQuery.class);
            TaskCandidateQuery taskCandidate = taskQuery.getTaskCandidate();
            if (taskCandidate != null && StrUtil.isNotBlank(taskCandidate.getCandidateExpression())) {
                String candidateExpression = taskCandidate.getCandidateExpression();
                Object result = ActivityUtils.calculateExpression(candidateExpression, delegateTask.getExecution());
                if (result != null) {
                    String taskId = delegateTask.getId();
                    Collection candidateUser = CollUtil.newArrayList();
                    if (result instanceof Collection) {
                        candidateUser = CollUtil.addAll(candidateUser, result);
                    } else if (result instanceof String) {
                        candidateUser = CollUtil.addAll(candidateUser, StrUtil.split(result.toString(), ","));
                    }

                    // 将候选人表达式计算结果 追加到当前任务
                    candidateUser.stream().forEach(e -> taskService.addCandidateUser(taskId, e.toString()));
                }
            }

        }
    }
}
